$(".selectpicker").selectpicker({
    noneSelectedText: '请选择'//默认显示内容
});


//添加测试用例内测试集变化时，级联变化
$("select#belongTestSuit_a").change(function () {
    $("#testcase_interface_a").empty();
    var testsuit_id = $(this).val();
    // 获取当前测试集所属项目id
    var project_id = '';
    $.ajax({
        url: '/flytest/test/testsuit?id=' + testsuit_id,
        type: 'get',
        async: false,
        dataType: 'json',
        success: function (result) {
            project_id = result.testsuit.belongTo;
        }
    });
    // 根据项目id获取当前项目下所有接口
    $.ajax({
        url: '/flytest/proj/interface/project?projectId=' + project_id,
        type: 'get',
        async: false,
        dataType: 'json',
        success: function (result) {
            var interfaces = result.interfaces;
            console.log(interfaces);
            var select = $("#testcase_interface_a");
            // 添加接口uri到接口下拉框
            for (var i = 0; i < interfaces.length; i++) {
                select.append("<option value='{interfaceId}'>{uri}</option>".signMix(interfaces[i]));
            }
            $('.selectpicker').selectpicker('val', '请选择');
            $('.selectpicker').selectpicker('refresh');
        }
    });
});

//更新测试用例内测试集变化时，级联变化
$("select#belongTestSuit_u").change(function () {
    $("#testcase_interface_u").empty();
    var testsuit_id = $(this).val();
    // 获取当前测试集所属项目id
    var project_id = '';
    $.ajax({
        url: '/flytest/test/testsuit?id=' + testsuit_id,
        type: 'get',
        async: false,
        dataType: 'json',
        success: function (result) {
            project_id = result.testsuit.belongTo;
        }
    });
    // 根据项目id获取当前项目下所有接口
    $.ajax({
        url: '/flytest/proj/interface/project?projectId=' + project_id,
        type: 'get',
        async: false,
        dataType: 'json',
        success: function (result) {
            var interfaces = result.interfaces;
            console.log(interfaces);
            var select = $("#testcase_interface_u");
            // 添加接口uri到接口下拉框
            for (var i = 0; i < interfaces.length; i++) {
                select.append("<option value='{interfaceId}'>{uri}</option>".signMix(interfaces[i]));
            }
            $('.selectpicker').selectpicker('val', '请选择');
            $('.selectpicker').selectpicker('refresh');
        }
    });
});

function showJsonEditor(elementId) {
    var example = "[\n" +
        "    {\n" +
        "        \"config\": {\n" +
        "            \"name\": \"testcase description\",\n" +
        "            \"parameters\": [\n" +
        "                {\"user_id\": [1001, 1002, 1003, 1004]}\n" +
        "            ],\n" +
        "            \"variables\": [\n" +
        "                {\"device_sn\": \"${gen_random_string(15)}\"},\n" +
        "                {\"user_id\": 1000}\n" +
        "            ],\n" +
        "            \"request\": {\n" +
        "                \"base_url\": \"http://127.0.0.1:5000\",\n" +
        "                \"headers\": {\n" +
        "                    \"User-Agent\": \"python-requests/2.18.4\",\n" +
        "                    \"device_sn\": \"$device_sn\",\n" +
        "                    \"Content-Type\": \"application/json\"\n" +
        "                }\n" +
        "            }\n" +
        "        }\n" +
        "    },\n" +
        "    {\n" +
        "        \"test\": {\n" +
        "            \"name\": \"/api/get-token\",\n" +
        "            \"variables\": [\n" +
        "                {\"user_agent\": \"iOS/10.3\"},\n" +
        "                {\"os_platform\": \"ios\"},\n" +
        "                {\"app_version\": \"2.8.6\"}\n" +
        "            ],\n" +
        "            \"request\": {\n" +
        "                \"url\": \"/api/get-token\",\n" +
        "                \"headers\": {\n" +
        "                    \"user_agent\": \"$user_agent\",\n" +
        "                    \"os_platform\": \"$os_platform\",\n" +
        "                    \"app_version\": \"$app_version\"\n" +
        "                },\n" +
        "                \"method\": \"POST\",\n" +
        "                \"json\": {\n" +
        "                    \"sign\": \"${get_sign($user_agent, $device_sn, $os_platform, $app_version)}\"\n" +
        "                }\n" +
        "            },\n" +
        "            \"extract\": [\n" +
        "                {\"token\": \"content.token\"}\n" +
        "            ],\n" +
        "            \"validate\": [\n" +
        "                {\"eq\": [\"status_code\", 200]},\n" +
        "                {\"eq\": [\"headers.Content-Type\", \"application/json\"]},\n" +
        "                {\"eq\": [\"content.success\", true]}\n" +
        "            ]\n" +
        "        }\n" +
        "    },\n" +
        "    {\n" +
        "        \"test\": {\n" +
        "            \"name\": \"/api/users/$user_id\",\n" +
        "            \"request\": {\n" +
        "                \"url\": \"/api/users/$user_id\",\n" +
        "                \"headers\": {\n" +
        "                    \"token\": \"$token\"\n" +
        "                },\n" +
        "                \"method\": \"POST\",\n" +
        "                \"json\": {\"name\": \"user1\", \"password\": \"123456\"}\n" +
        "            },\n" +
        "            \"validate\": [\n" +
        "                {\"eq\": [\"status_code\", 201]},\n" +
        "                {\"eq\": [\"headers.Content-Type\", \"application/json\"]},\n" +
        "                {\"eq\": [\"content.success\", true]},\n" +
        "                {\"eq\": [\"content.msg\", \"user created successfully.\"]}\n" +
        "            ]\n" +
        "        }\n" +
        "    }\n" +
        "]";
    var jsonString = JSON.parse(example);
    // create the editor
    var container = document.getElementById(elementId);
    var options = {
        mode: 'code',
        modes: ['code', 'form', 'text', 'tree', 'view'], // allowed modes
        onError: function (err) {
            alert(err.toString());
        }
    };
    return new JSONEditor(container, options, jsonString);
}


var jsonEditor_add = showJsonEditor('testcaseJsonEditor_a');
var jsonEditor_update = showJsonEditor('testcaseJsonEditor_u');


//  从本地加载json文件
$("#uploadFile").click(function () {
    //获取读取我文件的File对象
    var selectedFile = document.getElementById('loadJsonDocument').files[0];
    var name = selectedFile.name;//读取选中文件的文件名
    var size = selectedFile.size;//读取选中文件的大小
    console.log("文件名:" + name + "大小:" + size);
    var reader = new FileReader();//读取操作.
    reader.readAsText(selectedFile);//读取文件的内容,也可以读取文件的URL
    reader.onload = function () {
        //当读取完成后回调这个函数,然后此时文件的内容存储到了result中,直接操作即可
        var jsonstr = reader.result;
        var json = JSON.parse(jsonstr);
        jsonEditor_add.set(json);
    };
});

$("#uploadFile_u").click(function () {
    //获取读取我文件的File对象
    var selectedFile = document.getElementById('loadJsonDocument_u').files[0];
    var name = selectedFile.name;//读取选中文件的文件名
    var size = selectedFile.size;//读取选中文件的大小
    console.log("文件名:" + name + "大小:" + size);
    var reader = new FileReader();//读取操作.
    reader.readAsText(selectedFile);//读取文件的内容,也可以读取文件的URL
    reader.onload = function () {
        //当读取完成后回调这个函数,然后此时文件的内容存储到了result中,直接操作即可
        var jsonstr = reader.result;
        var json = JSON.parse(jsonstr);
        jsonEditor_update.set(json);
    };
});

// 新增测试用例按钮被点击时，触发设置测试集到下拉列表内
$("#add_new_testcase").click(function () {
    // 设置悬着文件控件样式
    $(':file').filestyle({
        buttonText: 'File',
        buttonName: 'btn-success'
    });


    // 获取所有测试集列表
    $.ajax({
        url: "/flytest/test/testsuit_list",
        type: "get",
        dataType: "json",
        success: function (result) {
            //console.log(result);
            // 设置测试集到下拉列表内
            var list = result.testsuits;
            console.log(list);
            var testsuitSelect = document.getElementById('belongTestSuit_a');
            var option = "";
            for (var i = 0; i < list.length; i++) {
                option = option + "<option value=\"{testSuitId}\">{suitName}</option>".signMix(list[i])
            }
            //console.log(option);
            testsuitSelect.innerHTML = option;
        }
    })
});

//点击修改按钮时，设置各项数据到modal内
function updateTestCaseModalShow(testcaseId) {
    // 设置悬着文件控件样式
    $(':file').filestyle({
        buttonText: 'File',
        buttonName: 'btn-success'
    });

    // 获取所有测试集列表
    $.ajax({
        url: "/flytest/test/testsuit_list",
        type: "get",
        async: false,
        dataType: "json",
        success: function (result) {
            //console.log(result);
            // 设置测试集到下拉列表内
            var list = result.testsuits;
            console.log(list);
            var testsuitSelect = document.getElementById('belongTestSuit_u');
            var option = "";
            for (var i = 0; i < list.length; i++) {
                option = option + "<option value=\"{testSuitId}\">{suitName}</option>".signMix(list[i])
            }
            //console.log(option);
            testsuitSelect.innerHTML = option;
        }
    });
    // 设置当前测试用例各项数值到各个控件内
    // first：获取当前测试用例数据
    $.ajax({
        url: '/flytest/test/testcase/' + testcaseId,
        type: 'get',
        dataType: 'json',
        success: function (res) {
            if (res.code === '200') {
                console.log(res.testcase);
                $("#testcaseId_u").val(res.testcase.testcaseId);
                $("#testcaseName_u").val(res.testcase.testcaseName);

                $("#belongTestSuit_u").val(res.testcase.testSuitId);
                //todo 设置下拉列表未调试好
                $("#testcase_interface_u").selectpicker('val', res.testcase.interfaceId);
                $("#testcase_desc_u").val(res.testcase.description);
                const jsonData = JSON.parse(res.testcase.jsonData);
                jsonEditor_update.set(jsonData);
            }
        }
    })
}


var jsonEditor_view = showJsonEditor('json_data_view_area');

function viewJsonData(data) {
    jsonEditor_view.set(JSON.parse(data));
}

// 点击保存按钮，添加测试用例
function addTestCase() {
    var base_form = $("#testcase_base_info_form_a").serialize();
    var json = jsonEditor_add.get();
    var data = base_form + '&jsonData=' + JSON.stringify(json);
    console.log(data);
    $.ajax({
        url: '/flytest/test/testcase',
        type: 'post',
        data: data,
        dataType: 'json',
        success: function (res) {
            if (res.code === '200') {
                window.location.href = '/flytest/test/testcases';
            }
        }
    })
}

// 点击更新按钮，更新测试用例
function updateTestCase() {
    var base_form = $("#testcase_base_info_form_u").serialize();
    var json = jsonEditor_update.get();
    var data = base_form + '&jsonData=' + JSON.stringify(json);
    console.log(data);
    $.ajax({
        url: '/flytest/test/testcase',
        type: 'put',
        data: data,
        dataType: 'json',
        success: function (res) {
            if (res.code === '200') {
                window.location.href = '/flytest/test/testcases';
            }
        }
    })
}

function deleteTestCase(id) {
    bootbox.confirm({
        message: "确认删除测试用例吗？",
        buttons: {
            confirm: {
                label: 'Yes',
                className: 'btn-success'
            },
            cancel: {
                label: 'No',
                className: 'btn-danger'
            }
        },
        callback: function (result) {
            console.log("will delete the testcase id : " + id);
            if (result) {
                $.ajax({
                    url: '/flytest/test/testcase/' + id,
                    type: 'delete',
                    dataType: 'json',
                    success: function (res) {
                        if (res.code === '200') {
                            sleep(500);
                            window.location.href = '/flytest/test/testcases';
                            swal("删除成功");
                        }
                    }
                })
            }

        }
    });
}

function runTestCase(id) {
    $("#fakeLoader").fakeLoader({
        timeToHide: 1000000, //加载效果的持续时间
        zIndex: "999",
        spinner: "spinner2",//可选值 'spinner1', 'spinner2', 'spinner3', 'spinner4', 'spinner5', 'spinner6', 'spinner7' 对应有7种效果
        bgColor: "#009688", //加载时的背景颜色
        // imagePath:"yourPath/customizedImage.gif" //自定义的加载图片
    });

    $.ajax({
        url: '/flytest/test/testcase/run?id=' + id,
        type: 'get',
        dataType: 'json',
        success: function (res) {
            if (res.code === '200') {
                //sleep(10000);
                //加载完关闭
                $("#fakeLoader").fakeLoader({
                    timeToHide: 1,
                    bgColor: "#009688",
                    spinner: "spinner2"
                });

                //window.location.href = '/flytest/test/testcases';
            }
        }
    });


}


